import { defineComponent } from 'vue';
import './index.less';
import { ActionSheet, Button, DatePicker, Icon, Popup } from 'vant';
import { dateFormatter } from '@/utils';

export default defineComponent({
  name: 'MButton',
  //   按钮类型，功能类型，是否需要border，右侧图标，按钮文字，按钮文字为空时使用placeholder，弹窗标题，数据源:[search:搜索项，list:弹窗列表]
  props: {
    type: { default: 'list' },
    function: { default: 'dialog' },
    border: { default: true },
    datekey: {},
    icon: { default: '' },
    content: { default: '' },
    placeholder: { default: '请选择' },
    title: { default: '标题' },
    data: { default: {} }
  },
  emits: ['search'],
  setup(props: any, { slots, emit }) {
    const { VITE_STATIC_URL } = import.meta.env;
    const show = ref(false);
    const popupShow = ref(false);
    const searchParams = ref({}) as AnyObject;
    searchParams.value[props.datekey] =
      props.datekey == 'year'
        ? [new Date().getFullYear()]
        : [new Date().getFullYear(), new Date().getMonth() + 1];
    const entrance = ref('');

    const confirmDate = (type: string, e: any) => {
      if (type == 'confirm') {
        searchParams.value[props.datekey] = e.selectedValues;
        if (entrance.value == 'direct') {
          Object.assign(props.data.search, searchParams.value);
          emit('search');
        }
      }
      popupShow.value = false;
      if (entrance.value == 'indirect') {
        show.value = true;
      }
      console.log(searchParams.value, props.datekey);
    };
    const handleDate = () => {
      entrance.value = 'indirect';
      popupShow.value = true;
      show.value = false;
    };
    const sheetItem = (item: AnyObject) => {
      if (item.type === 'list') {
        return (
          <div class="sheet_item">
            <p class="title">{item.title}</p>
            <ul class="flex-start">
              {item.list?.map((_item: any) => (
                <li
                  onClick={() => handleActive(_item, item)}
                  class={{
                    active: _item.value
                      ? searchParams.value[item.key] == _item.value
                      : searchParams.value[item.key] == _item
                  }}
                >
                  {_item.label || _item}
                </li>
              ))}
            </ul>
          </div>
        );
      } else {
        return (
          <div class="sheet_item">
            <p class="title">{item.title}</p>
            <div onClick={handleDate} class="time_controller flex-between">
              {props.data.search[props.datekey]
                ? dateFormatter(searchParams.value[props.datekey])
                : item.placeholder}
              <Icon name="arrow" />
            </div>
          </div>
        );
      }
    };
    const handleActive = (item: any, origin: any) => {
      if (origin.type !== 'list') return;
      const mergeObj = {
        [origin.key]:
          searchParams.value[origin.key] == item ? '' : item.value || item
      };

      Object.assign(searchParams.value, mergeObj);
      console.log(props.datekey, searchParams.value);
    };
    const openDialog = () => {
      console.log(props.data.list);

      show.value = true;
      Object.entries(props.data.search).forEach((item: any) => {
        item[1] && (searchParams.value[item[0]] = item[1]);
      });
      console.log(searchParams.value);

      // searchParams.value = JSON.parse(JSON.stringify(props.data.search));
    };
    const openPopup = () => {
      entrance.value = 'direct';
      popupShow.value = true;
    };
    const handleSearch = () => {
      show.value = false;
      Object.assign(props.data.search, searchParams.value);
      emit('search');
    };
    return () => (
      <>
        <button
          class={`mbutton flex-start comBtn ${
            props.content ? 'has_content' : 'no_content'
          } ${props.border ? 'border' : 'noborder'}`}
          onClick={props.type === 'list' ? openDialog : openPopup}
        >
          <span>{props.content || props.placeholder}</span>
          {props.icon ? (
            <img src={`${VITE_STATIC_URL}/tcpl/${props.icon}.png`} />
          ) : (
            <Icon name="arrow-down" />
          )}
        </button>

        <ActionSheet
          close-on-click-overlay={false}
          v-model:show={show.value}
          title={props.title}
          teleport="body"
        >
          <div class="sheet_content">
            {props.data.list?.map((item: AnyObject) => sheetItem(item))}
          </div>
          <Button class="sheet_btn" type="primary" onClick={handleSearch}>
            确定
          </Button>
        </ActionSheet>
        <Popup v-model:show={popupShow.value} position="bottom" teleport="body">
          <DatePicker
            maxDate={new Date()}
            onCancel={(e) => confirmDate('cancel', e)}
            onConfirm={(e) => confirmDate('confirm', e)}
            v-model={searchParams.value[props.datekey]}
            title={props.datekey == 'month' ? '选择年月' : '选择年'}
            columns-type={
              props.datekey == 'month' || props.datekey == 'dateTime'
                ? ['year', 'month']
                : ['year']
            }
          />
        </Popup>
      </>
    );
  }
});
